//
//  BaseViewController.m
//  QA
//
//  Created by Yoga on 2017/4/19.
//  Copyright © 2017年 ZDQK. All rights reserved.
//

#import "BaseViewController.h"
#import "LoginViewController.h"

@interface BaseViewController ()<UITextFieldDelegate>

@end

@implementation BaseViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
    [self setNavigationBarAlpha:1.0 animation:NO];
    
    [self.navigationController setNavigationBarHidden:NO animated:NO];
//    if([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {
//        [self setNeedsStatusBarAppearanceUpdate];
//    }
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:NO];
    //    [self.navigationController.navigationBar setBarTintColor:UIColorFromRGB(0xffffff)];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
}
#pragma mark - method
- (void)hideKeyboard:(id)sender {
    [self.view endEditing:YES];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    _keyboardAnimationDuration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    _keyboardBenginFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    _keyboardEndFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
}
- (void)keyboardDidShow:(NSNotification *)notification {
    _keyboardAnimationDuration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    _keyboardBenginFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    _keyboardEndFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
}
- (void)keyboardWillHide:(NSNotification *)notification {
    _keyboardAnimationDuration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    _keyboardBenginFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    _keyboardEndFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.navigationController.navigationBar setShadowImage:[UIImage imageWithColor:[UIColor grayE5Color]]];
    [self hiddenShadowImage:YES];
    
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar setBarTintColor:[UIColor NavBarColor]];
    [self.navigationController.navigationBar setTintColor:[UIColor grayTextColor]];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHex:0x030303 alpha:1.0],NSFontAttributeName:[UIFont systemFontOfSize:17.0f]}];
//    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    [self showBackButtonItem];
}
- (void)hiddenShadowImage:(BOOL)isHidden {
    // 找出并隐藏navBar底部黑线
    UIImageView *shadowImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    if (shadowImageView) shadowImageView.hidden = isHidden; // 存在便隐藏
}
// 找出一个view的子控件中高度小于等于1像素的UIImageView控件
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && CGRectGetHeight(view.bounds) <= 1.f) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

- (void)showBackButtonItem {
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(disMissSelf)];
    self.navigationItem.leftBarButtonItem = leftItem;
}

- (void)setNavigationBarAlpha:(CGFloat)alpha animation:(BOOL)animation {
    if (animation) {
        [UIView animateWithDuration:0.2 animations:^{
//            self.navigationController.navigationBar.subviews[0].alpha = alpha;
//            [[self.navigationController.navigationBar.subviews lastObject] setAlpha:alpha];
            [self.navigationController.navigationBar setAlpha:alpha];
        }];
    } else {
        
//        self.navigationController.navigationBar.subviews[0].alpha = alpha;
//        [[self.navigationController.navigationBar.subviews lastObject] setAlpha:alpha];
        [self.navigationController.navigationBar setAlpha:alpha];
    }
    
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
//    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
//    [[UINavigationBar appearance] setTranslucent:NO];
}
- (void)setStatusBarStyle:(UIStatusBarStyle)style animated:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarStyle:style animated:animated];
}

- (void)disMissSelf {
    if(self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)popToRootViewController {
    if (self.navigationController) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
- (void)popToRoot {
    [self dismissViewControllerAnimated:NO completion:nil];
//    if ([self.presentingViewController isKindOfClass:[MineHomeViewController class]]) {
//        [self.presentingViewController viewWillAppear:NO];
//        return;
//    }
//    else
        if ([self.presentingViewController isKindOfClass:[BaseTabbarViewController class]]) {
        UIViewController *topVC = ((UINavigationController *)((BaseTabbarViewController *)[UIApplication sharedApplication].keyWindow.rootViewController).selectedViewController).topViewController;
        [topVC.navigationController popToRootViewControllerAnimated:YES];
        return;
    }
    else if (self.presentingViewController.navigationController) {
        [self.presentingViewController.navigationController popToRootViewControllerAnimated:YES];
        return;
    }
    else {
        [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
    }
}
- (void)showAlertMessage:(NSString *)message {
    self.alertC = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (self.alertBlock) {
            self.alertBlock(action.title);
        }
    }];
    [_alertC addAction:action];
    [self presentViewController:_alertC animated:YES completion:nil];
}
- (void)showAlertTextFieldWithTitleArray:(NSArray *)buttonTitleArray title:(NSString *)title {
    self.alertC = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    for (NSString *str in buttonTitleArray) {
        UIAlertActionStyle style = UIAlertActionStyleDestructive;
        if ([str isEqualToString:@"取消"] || [str isEqualToString:@"拒绝"]) {
            style = UIAlertActionStyleCancel;
        }
        UIAlertAction *action = [UIAlertAction actionWithTitle:str style:style handler:^(UIAlertAction * _Nonnull action) {
            if (self.alertBlock) {
                self.alertBlock(action.title);
            }
            
        }];
        [_alertC addAction:action];
    }
    __weak typeof(self) weakSelf = self;
    [_alertC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.delegate = weakSelf;
        textField.tag = 999999;
    }];
    
    [self presentViewController:_alertC animated:YES completion:nil];
}
- (void)showAlertWithTitleArray:(NSArray *)buttonTitleArray title:(NSString *)title message:(NSString *)message alertStyle:(UIAlertControllerStyle)alertStyle{
    self.alertC = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:alertStyle];
    
    for (NSString *str in buttonTitleArray) {
        UIAlertActionStyle style;
        if (alertStyle == UIAlertControllerStyleAlert) {
            style = UIAlertActionStyleDestructive;  // alert
        } else {
            style = UIAlertActionStyleDefault;      // sheet
        }
        
        if ([str isEqualToString:@"取消"] || [str isEqualToString:@"拒绝"] || [str containsString:@"否"]) {
            style = UIAlertActionStyleCancel;
        }
        UIAlertAction *action = [UIAlertAction actionWithTitle:str style:style handler:^(UIAlertAction * _Nonnull action) {
            if (self.alertBlock) {
                self.alertBlock(action.title);
            }
        }];
        [_alertC addAction:action];
    }
    [self presentViewController:_alertC animated:YES completion:nil];
}

- (void)showPicture:(UIView *)view index:(NSInteger)index urls:(NSArray *)urls{
    NSMutableArray *urlArr = [NSMutableArray array];
    for (NSString *imgUrl in urls) {
        NSURL *url = [NSURL URLWithString:imgUrl];
        [urlArr addObject:url];
    }
    //    IDMPhoto *photo = [IDMPhoto photoWithURL:[NSURL URLWithString:imgUrl]];
    
    IDMPhotoBrowser *browser = [[IDMPhotoBrowser alloc] initWithPhotoURLs:urlArr animatedFromView:view];
    //    IDMPhotoBrowser *browser = [[IDMPhotoBrowser alloc] initWithPhotos:@[photo] animatedFromView:self.imageView];
    browser.displayActionButton = NO;
    browser.displayArrowButton = NO;
    browser.displayCounterLabel = NO;
    browser.displayDoneButton = NO;
    browser.doneButtonImage = [UIImage imageNamed:@"out"];
    if ([view isKindOfClass:[UIImageView class]]) {
        UIImageView *imageView = (UIImageView *)view;
        browser.scaleImage = imageView.image;
    }
    browser.dismissOnTouch = YES;
    [browser setInitialPageIndex:index];
    [self presentViewController:browser animated:YES completion:nil];
}

- (void)settingTableViewAdjustment:(UITableView *)tableView {
    // tableView 偏移20/64适配
    if (@available(iOS 11.0, *)) {
        tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//UIScrollView也适用
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

- (void)showShareAlert:(NSMutableArray *)imgs withGoodsDescription:(NSString *)goodsDescription withGid:(NSString *)gid {
    NSMutableArray *imageArr = [NSMutableArray array];
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    for (NSString *url in imgs) {
        [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:url] options:SDWebImageDownloaderUseNSURLCache progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            
        } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
            if (image) {
                [imageArr addObject:image];
            }
            if (imageArr.count == imgs.count) {
                [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
                [weakSelf showShareWeChatWithImages:imageArr];
                [weakSelf pasteboardText:goodsDescription];
                [weakSelf sendGoodsShare:gid];
            }
        }];
    }
}

- (void)showShareAlertWithImages:(NSMutableArray <UIImage *> *)imgs withGoodsDescription:(NSString *)goodsDescription withGid:(NSString *)gid {
    [self showShareWeChatWithImages:imgs];
    [self pasteboardText:goodsDescription];
    [self sendGoodsShare:gid];
}


- (void)showShareWeChatWithImages:(NSMutableArray *)imgs {
    UIActivityViewController *activityView = [[UIActivityViewController alloc] initWithActivityItems:imgs applicationActivities:nil];
    activityView.excludedActivityTypes = @[UIActivityTypeMessage,
                                           UIActivityTypeMail,
                                           UIActivityTypePrint,
                                           UIActivityTypeCopyToPasteboard,
                                           UIActivityTypeAssignToContact,
                                           UIActivityTypeSaveToCameraRoll,
                                           UIActivityTypeAddToReadingList,
                                           UIActivityTypePostToFlickr,
                                           UIActivityTypePostToVimeo,
                                           UIActivityTypeAirDrop,
                                           UIActivityTypeOpenInIBooks];
    [self presentViewController:activityView animated:YES completion:nil];
}

- (void)pasteboardText:(NSString *)text {
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = text;
    
    [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"商品描述已复制，可以粘贴到朋友圈描述中" animated:YES];
}

- (void)sendGoodsShare:(NSString *)gid {
    if (gid.length == 0) {
        return;
    }
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:gid forKey:@"gid"];
    [MYAFNetworking POST:URL_Goods_Share parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        
    }];
}
- (CGFloat)getNavAndStatusHeight {
    // 状态栏(statusbar)
    CGFloat StatusRectH = [self getStatusHeight];
    
    //标题栏
    CGFloat NavRectH = [self getNavHeight];
    
    return StatusRectH+NavRectH;
}
- (CGFloat)getStatusHeight {
    // 状态栏(statusbar)
    CGRect StatusRect = [[UIApplication sharedApplication] statusBarFrame];
    return StatusRect.size.height;
}
- (CGFloat)getNavHeight {
    //标题栏
    CGRect NavRect = self.navigationController.navigationBar.frame;
    return NavRect.size.height;
}

- (void)hideNavigationController {
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
    self.navigationController.view.backgroundColor = [UIColor clearColor];
    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
    self.navigationController.navigationBar.translucent = YES;    
}

- (void)uploadImage:(UIImage *)image success:(void (^)(NSString *imageUrl))success {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking UPLoad:UpLoad_URL images:image progress:nil success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            NSString *imageUrl = responseObject[@"data"];
            success(imageUrl);
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}

- (void)goToServiceChat {
    if (![self checkLogin]) {
        return;
    }
    
    // 会话来源
    QYSource *source = [[QYSource alloc] init];
    source.title = QiYuAppName;
    //source.urlString = @"";
    // 会话界面
    QYSessionViewController *sessionViewController = [[QYSDK sharedSDK] sessionViewController];
    sessionViewController.sessionTitle = @"客服";
    sessionViewController.source = source;
    sessionViewController.hidesBottomBarWhenPushed = YES;
    sessionViewController.navigationItem.leftBarButtonItem =
    [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(serviceDismiss)];
    
    BaseNavigationViewController *nav = [[BaseNavigationViewController alloc] initWithRootViewController:sessionViewController];
    
    [nav.navigationBar setBarTintColor:[UIColor NavBarColor]];
    [nav.navigationBar setTintColor:[UIColor grayTextColor]];
    [nav.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHex:0x030303 alpha:1.0],NSFontAttributeName:[UIFont systemFontOfSize:17.0f]}];
    
    [self presentViewController:nav animated:YES completion:nil];
}
- (void)serviceDismiss {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (BOOL)checkLogin {
    if (![UserInfo shareInstance].isLogin) {
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        BaseNavigationViewController *nav = [[BaseNavigationViewController alloc] initWithRootViewController:loginVC];
        [self presentViewController:nav animated:YES completion:nil];
        return NO;
    }
    return YES;
}
- (BOOL)checkOpen {
    if (![UserInfo shareInstance].isOpen) {
        [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"该功能暂未开放~" animated:YES];
        return NO;
    }
    return YES;
}
#pragma mark - textFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField.tag == 999999) {
        if ([string isEqualToString:@""]) {
            return YES;
        }
        if (textField.text.length >= 120) {
            return NO;
        } else {
            return YES;
        }
    }
    return YES;
}

@end
